package cn.smbms.controller;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;


import cn.smbms.pojo.User;
import cn.smbms.service.UserService;

@Controller
public class LoginController {
	
	@Resource
	private UserService userService;
	
	
	@RequestMapping(value="/login")
	public String login(){
		return "login";
	}
	@RequestMapping(value = "/tologin",method=RequestMethod.POST)
	public String tologin(@RequestParam String userCode,@RequestParam String userPassword,HttpServletRequest request,HttpSession session) {
		User user=userService.login(userCode, userPassword);
		if (user==null) {
			request.setAttribute("error","密码或用户名错误");
			return "login";
		}else {
			session.setAttribute("userSession", user);
		}
		return "redirect:serlogin";
	}
	@RequestMapping(value="serlogin")
	public String serlogin() {
		return "frame";
	}
	@RequestMapping(value="pwd.sm")
	public String pwd() {
		return "pwdmodify";
	}
	
	@RequestMapping(value="pwdmy")
	@ResponseBody
	public Object pwdmy(@RequestParam String oldpassword,HttpSession session) {
		HashMap<String, Object> map=new HashMap<String,Object>();
		if (session.getAttribute("userSession")==null) {
			map.put("result", "sessionerror");
		}else {
			User loginUser=(User)session.getAttribute("userSession");
			if (loginUser.getUserPassword().equals(oldpassword)) {
				map.put("result", "true");
			}else if (!loginUser.getUserPassword().equals(oldpassword)) {
				map.put("result", "false");
			}else {
				map.put("result", "error");
			}
		}
		return JSONArray.toJSONString(map);
	}
	@RequestMapping(value="upwd")
	public String upwd(@RequestParam String newpassword,HttpSession session) {
		User user=(User)session.getAttribute("userSession");
		int count=userService.updatePwd(newpassword, user.getId());
		if (count>0) {
			return "redirect:login";
		}else {
			session.setAttribute("message", "修改密码失败");
		}
		return "pwdmodify";
	}
}
